/*
 * File Name：ProgressButton.java
 * Copyright：Copyright 2008-2013 CiWong.Inc. All Rights Reserved.
 * Description： ProgressButton.java
 * Modify By：PLA-ZJLIU
 * Modify Date：2013-12-15
 * Modify Type：Add
 */
package com.ciwong.mobilelib.widget;

import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.mobilelib.R;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

/**
 * 带圆形进度条的按钮
 * 
 * @author PLA-ZJLIU
 * @version ciwong v.1.0 2013-12-15
 * @since ciwong v.1.0
 */
public class ProgressButtonHearing extends Button implements OnClickListener
{
    private static final int PLAY_STATUS_NORMAL = 0;

    private static final int PLAY_STATUS_PLAYING = 1;

    private static final int PLAY_STATUS_BUFFERING = 2;

    private int progressColor;

    private Drawable bufferImage;

    private AudioPlayer mPlayer;

    private boolean isStart, isPuase;

    private int playStatus;

    private Handler mHandler = new Handler();

    private float sweepAngle;

    private Paint mPaint;

    private RectF oval;

    private Rect bufferingRect;

    private float mPainStroke;

    private float rotateDegrees;

    private boolean isInited;

    private Drawable soundPlay, soundStop;

    private boolean isStarted, isPlaying;

    private OnClickListener listener;

    // private int normalCount;
    private boolean isStatusEnable;

    /**
     * 构造函数
     *
     * @param context
     *            上下文
     */
    public ProgressButtonHearing(Context context)
    {
        super(context);
        init();
    }

    /**
     *
     * 构造函数
     *
     * @param context
     *            上下文
     * @param attrs
     *            {@link AttributeSet}
     */
    public ProgressButtonHearing(Context context, AttributeSet attrs)
    {
        super(context, attrs);
        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.progress_button);
        init(a);
        init();
    }

    /**
     * 构造函数
     *
     * @param context
     *            上下文
     * @param attrs
     *            {@link AttributeSet}
     * @param defStyle
     *            样式
     */
    public ProgressButtonHearing(Context context, AttributeSet attrs, int defStyle)
    {
        super(context, attrs, defStyle);
        TypedArray a = getContext().obtainStyledAttributes(attrs,
                R.styleable.progress_button);
        init(a);
        init();
    }

    private void init(TypedArray a)
    {
        progressColor = a.getColor(R.styleable.progress_button_progress_color,
                Color.rgb(152, 212, 119));
        mPainStroke = a.getDimension(R.styleable.progress_button_stroke,
                TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 3,
                        getResources().getDisplayMetrics()));
        bufferImage = a
                .getDrawable(R.styleable.progress_button_buffering_image);
        soundPlay = a.getDrawable(R.styleable.progress_button_sound_play);
        soundStop = a.getDrawable(R.styleable.progress_button_sound_stop);
        a.recycle();
    }

    private void init()
    {
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setStyle(Style.STROKE);
        mPaint.setColor(progressColor);
        mPaint.setStrokeWidth(mPainStroke);
        if (bufferImage == null)
        {
            bufferImage = getContext().getResources().getDrawable(
                    R.mipmap.libs_loading);
        }
        if (soundPlay == null)
        {
            soundPlay = getContext().getResources().getDrawable(
                    R.mipmap.hearing_btn_play);
        }
        if (soundStop == null)
        {
            soundStop = getContext().getResources().getDrawable(
                    R.mipmap.hearing_btn_stop);
        }
        setBackgroundDrawable(soundPlay);
        isStatusEnable = true;
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh)
    {
        super.onSizeChanged(w, h, oldw, oldh);
        if (w != 0 && h != 0)
        {
            isInited = true;
        }
    }

//    private void soundStopStatus()
//    {
//        if (getBackground() != soundStop)
//        {
//            setBackgroundDrawable(soundStop);
//        }
//    }

    private void progressing()
    {
        CWLog.i("debug", "playStatus:" + playStatus + "    isStart:" + isStart
                + "    isPuase:" + isPuase);
        try {

            if (mPlayer != null && isStart && !isPuase)
            {
                if (mPlayer.isPlaying())
                {
                    playStatus = PLAY_STATUS_PLAYING;
                    long total = mPlayer.getDuration();
                    long progress = mPlayer.getCurrentPosition();
                    sweepAngle = (float) progress / (float) total * 360;
                    // normalCount = 0;
                }
                else if (mPlayer.isBuffering())
                {
                    playStatus = PLAY_STATUS_BUFFERING;
                    rotateDegrees += 20;
                    if (rotateDegrees > 360)
                    {
                        rotateDegrees = 0;
                    }
                    // normalCount = 0;
                }
                else
                {
                    playStatus = PLAY_STATUS_NORMAL;
                }
                if (playStatus != PLAY_STATUS_NORMAL)
                {
                    mHandler.postDelayed(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            progressing();
                        }
                    }, playStatus == PLAY_STATUS_BUFFERING ? 80 : 200);
                    // normalCount++;
                }
                else
                {
                    stop();
                }
                if (isInited)
                {
                    postInvalidate();
                }
            }
            else
            {
                if (mPlayer != null && mPlayer.isPlaying())
                {
                    isStart = false;
                }
                isStarted = false;
                CWLog.d("debug", "mPlayer:" + mPlayer + "    isStart:" + isStart
                        + "     isPuase:" + isPuase);
                invalidate();
            }

        } catch (IllegalStateException e) {

        }



    }

    /**
     * 当前播放进度是否有效
     * 
     * @return 当前播放进度是否有效
     */
    public boolean isStatusEnable()
    {
        return isStatusEnable;
    }

    /**
     * 设置当前播放进度是否有效
     * 
     * @param enable
     *            是否有效
     */
    public void setStatusEnable(boolean enable)
    {
        this.isStatusEnable = enable;
    }

    @Override
    public void setOnClickListener(OnClickListener l)
    {
        super.setOnClickListener(this);
        listener = l;
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);
        int w = getMeasuredWidth();
        int h = getMeasuredHeight();
        int temp = (int) (mPainStroke / 2 + 2);
        if (isStart && isStatusEnable)
        {
            if (playStatus == PLAY_STATUS_PLAYING)
            {
//                soundStopStatus();
                if (oval == null)
                {
                    oval = new RectF(temp, temp, w - temp, h - temp);
                }
                canvas.drawArc(oval, 0, sweepAngle, false, mPaint);
            }
            else if (playStatus == PLAY_STATUS_BUFFERING)
            {
//                soundStopStatus();
                if (bufferingRect == null)
                {
                    bufferingRect = new Rect();
                    bufferingRect = new Rect(0, 0, w, h);
                    CWLog.d("debug",
                            "bufferingRect:" + bufferingRect
                                    + "    exactCenterX:"
                                    + bufferingRect.exactCenterX()
                                    + "      exactCenterY:"
                                    + bufferingRect.exactCenterY());
                    bufferImage.setBounds(bufferingRect);
                }
                canvas.save();
                canvas.rotate(rotateDegrees, bufferingRect.exactCenterX(),
                        bufferingRect.exactCenterY());
                bufferImage.draw(canvas);
                canvas.restore();
            }
        }
    }

    /**
     * 开始
     * 
     */
    public void start()
    {
        isPuase = false;
        isStatusEnable = true;
        isStart = true;
        setBackgroundDrawable(soundStop);
        if (isStarted)
        {
            return;
        }
        CWLog.d("debug", "start isPlaying:" + isPlaying);
        isStarted = true;
        progressing();
    }

    /**
     * 暂停
     * 
     */
    public void puase()
    {
        isPuase = true;
        progressing();
    }

    /**
     * 暂停后继续
     * 
     */
    public void resume()
    {
        isPuase = false;
        progressing();
    }

    /**
     * 停止
     * 
     */
    public void stop()
    {
        isPuase = false;
        isStart = false;
        isPlaying = true;
//        setBackgroundDrawable(soundPlay);
        progressing();
    }

    public void release()
    {
        if (mHandler != null)
        {
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * 设置进度条颜色
     * 
     * @param color
     *            进度条的颜色
     */
    public void setProgressColor(int color)
    {
        progressColor = color;
        if (mPaint != null)
        {
            mPaint.setColor(progressColor);
        }
    }

    /**
     * 设置进度条的宽度
     * 
     * @param strole
     *            进度条的宽度
     */
    public void setStrole(int strole)
    {
        mPainStroke = strole;
        if (mPaint != null)
        {
            mPaint.setStrokeWidth(mPainStroke);
        }
    }

    /**
     * 设置播放器
     * 
     * @param player
     *            {@link AudioPlayer}
     */
    public void setAudioPlayer(AudioPlayer player)
    {
        mPlayer = player;
    }

    @Override
    public void onClick(View v)
    {
        if (v == this)
        {
            if (isStarted)
            {
                CWLog.i("debug", "isPlaying:" + isPlaying);
                if (isPlaying)
                {
                    isPlaying = false;
                    isStart = true;
                    isPuase = false;
//                    setBackgroundDrawable(soundStop);
                    sweepAngle = 0;
                    mHandler.postDelayed(new Runnable()
                    {
                        @Override
                        public void run()
                        {
                            progressing();
                        }
                    }, 100);
                }
                else
                {
                    isPlaying = true;
                    stop();
                }
            }
            if (listener != null)
            {
                listener.onClick(v);
            }
        }
    }

    public void setPlayBtn()
    {
        setBackgroundDrawable(soundPlay);
    }

    public void setPauseBtn()
    {
        setBackgroundDrawable(soundStop);
    }

}
